package com.hsylient.javase.chapter12.demo01.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.util.Scanner;

//客户端B
public class ChatB {
	public static void main(String[] args) {
		// 控制台输入
		Scanner input = new Scanner(System.in);

		try (// 客户端B监听7777端口
				DatagramSocket socket = new DatagramSocket(7777)) {
			// 封装成DatagramPacket对象(数据包)
			DatagramPacket sendPacket = new DatagramPacket(new byte[1024], 1024,
					new InetSocketAddress("192.168.1.104", 8888));// 对方的IP地址和端口号
			DatagramPacket receivePacket = new DatagramPacket(new byte[1024], 1024);

			while (true) {
				// 接收数据包
				socket.receive(receivePacket);
				String receiveContent = new String(receivePacket.getData(), receivePacket.getOffset(),
						receivePacket.getLength());
				if (receiveContent.equals("over")) {
					System.out.println("对方退出了聊天......");
					break;
				}
				System.out.println("黄涛: " + receiveContent);

				// 发送数据包
				System.out.print("孟令军: ");
				String sendContent = input.nextLine();
				sendPacket.setData(sendContent.getBytes());
				socket.send(sendPacket);
				if (sendContent.equals("over")) {
					System.out.println("你退出了聊天......");
					break;
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}

